<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class AuthApiController extends BaseApiController
{
    /**
     * 微信公众号H5授权登录
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function wechatH5Login(Request $request): JsonResponse
    {
        try {
            // 从param对象中获取参数
            $code = $this->getRequiredParam($request, 'code', '缺少微信授权码');

            // 调用UserController的getUser方法来处理微信授权
            $userController = new \App\Http\Controllers\Api\UserController();
            
            // 设置请求参数，模拟UserController需要的参数格式
            $originalRequest = request();
            $originalRequest->merge(['code' => $code]);
            
            // 调用getUser方法
            $result = $userController->getUser();
            
            // 检查结果
            if ($result && isset($result->getData()->data)) {
                $userInfo = $result->getData()->data;
                
                return response()->json([
                    'result' => 1,
                    'msg' => '授权成功',
                    'data' => [
                        'openid' => $userInfo->openid ?? '',
                        'access_token' => $userInfo->access_token ?? '',
                        'user_info' => [
                            'nickname' => $userInfo->nickname ?? '微信用户',
                            'avatar' => $userInfo->headimgurl ?? 'https://example.com/default-avatar.jpg',
                            'sex' => $userInfo->sex ?? 1,
                            'city' => $userInfo->city ?? '武汉',
                            'province' => $userInfo->province ?? '湖北',
                            'country' => $userInfo->country ?? '中国'
                        ]
                    ]
                ]);
            } else {
                return response()->json([
                    'result' => 0,
                    'msg' => '获取用户信息失败',
                    'data' => null
                ], 400);
            }

        } catch (\InvalidArgumentException $e) {
            return response()->json([
                'result' => 0,
                'msg' => $e->getMessage(),
                'data' => null
            ], 400);
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg' => '服务器错误: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 微信小程序登录
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function wechatLogin(Request $request): JsonResponse
    {
        try {
            // 从param对象中获取参数
            $code = $this->getRequiredParam($request, 'code', '缺少微信授权码');
            $encryptedData = $this->getRequiredParam($request, 'encrypted_data', '缺少加密数据');
            $iv = $this->getRequiredParam($request, 'iv', '缺少初始向量');

            // 模拟微信登录成功
            $token = 'wechat_token_' . time();
            $openid = 'openid_' . rand(100000, 999999);
            
            return response()->json([
                'code' => 200,
                'message' => '登录成功',
                'data' => [
                    'token' => $token,
                    'user_info' => [
                        'openid' => $openid,
                        'nickname' => '微信用户',
                        'avatar' => 'https://example.com/default-avatar.jpg',
                        'is_bound_phone' => false
                    ]
                ]
            ]);

        } catch (\InvalidArgumentException $e) {
            return response()->json([
                'code' => 400,
                'message' => $e->getMessage(),
                'data' => null
            ], 400);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 500,
                'message' => '服务器错误',
                'data' => null
            ], 500);
        }
    }

    /**
     * 发送手机验证码
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function sendSmsCode(Request $request): JsonResponse
    {
        try {
            // 从param对象中获取手机号
            $phone = $this->getRequiredParam($request, 'phone', '缺少手机号');
            
            // 验证手机号格式
            if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
                return response()->json([
                    'code' => 422,
                    'message' => '手机号格式不正确',
                    'data' => null
                ], 422);
            }
            
            // 模拟发送验证码
            $code = rand(100000, 999999);
            
            return response()->json([
                'code' => 200,
                'message' => '验证码发送成功',
                'data' => [
                    'phone' => $phone,
                    'expires_in' => 300, // 5分钟过期
                    'message' => "验证码已发送至 {$phone}，请注意查收"
                ]
            ]);

        } catch (\InvalidArgumentException $e) {
            return response()->json([
                'code' => 400,
                'message' => $e->getMessage(),
                'data' => null
            ], 400);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 500,
                'message' => '服务器错误',
                'data' => null
            ], 500);
        }
    }

    /**
     * 绑定手机号
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function bindPhone(Request $request): JsonResponse
    {
        try {
            // 从param对象中获取参数
            $phone = $this->getRequiredParam($request, 'phone', '缺少手机号');
            $smsCode = $this->getRequiredParam($request, 'sms_code', '缺少验证码');
            $token = $this->getRequiredParam($request, 'token', '缺少登录令牌');

            // 验证手机号格式
            if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
                return response()->json([
                    'code' => 422,
                    'message' => '手机号格式不正确',
                    'data' => null
                ], 422);
            }

            // 模拟验证码验证
            if ($smsCode !== '123456') {
                return response()->json([
                    'code' => 400,
                    'message' => '验证码错误',
                    'data' => null
                ], 400);
            }

            // 模拟绑定成功
            return response()->json([
                'code' => 200,
                'message' => '手机号绑定成功',
                'data' => [
                    'phone' => $phone,
                    'is_bound' => true,
                    'message' => '手机号绑定成功，可以使用手机号登录'
                ]
            ]);

        } catch (\InvalidArgumentException $e) {
            return response()->json([
                'code' => 400,
                'message' => $e->getMessage(),
                'data' => null
            ], 400);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 500,
                'message' => '服务器错误',
                'data' => null
            ], 500);
        }
    }

    /**
     * 手机号登录
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function phoneLogin(Request $request): JsonResponse
    {
        try {
            // 从param对象中获取参数
            $phone = $this->getRequiredParam($request, 'phone', '缺少手机号');
            $smsCode = $this->getRequiredParam($request, 'sms_code', '缺少验证码');

            // 验证手机号格式
            if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
                return response()->json([
                    'code' => 422,
                    'message' => '手机号格式不正确',
                    'data' => null
                ], 422);
            }

            // 模拟验证码验证
            if ($smsCode !== '123456') {
                return response()->json([
                    'code' => 400,
                    'message' => '验证码错误',
                    'data' => null
                ], 400);
            }

            // 模拟登录成功
            $token = 'phone_token_' . time();
            
            return response()->json([
                'code' => 200,
                'message' => '登录成功',
                'data' => [
                    'token' => $token,
                    'user_info' => [
                        'phone' => $phone,
                        'nickname' => '用户' . substr($phone, -4),
                        'avatar' => 'https://example.com/default-avatar.jpg',
                        'is_bound_phone' => true
                    ]
                ]
            ]);

        } catch (\InvalidArgumentException $e) {
            return response()->json([
                'code' => 400,
                'message' => $e->getMessage(),
                'data' => null
            ], 400);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 500,
                'message' => '服务器错误',
                'data' => null
            ], 500);
        }
    }

    /**
     * 刷新token
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function refreshToken(Request $request): JsonResponse
    {
        try {
            $oldToken = $request->get('token');
            
            if (!$oldToken) {
                return response()->json([
                    'code' => 400,
                    'message' => '缺少token参数',
                    'data' => null
                ], 400);
            }

            // 生成新token
            $newToken = 'new_token_' . time();
            
            return response()->json([
                'code' => 200,
                'message' => 'token刷新成功',
                'data' => [
                    'token' => $newToken,
                    'expires_in' => 7200 // 2小时过期
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'code' => 500,
                'message' => '服务器错误',
                'data' => null
            ], 500);
        }
    }

    /**
     * 退出登录
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function logout(Request $request): JsonResponse
    {
        try {
            $token = $request->get('token');
            
            if (!$token) {
                return response()->json([
                    'code' => 400,
                    'message' => '缺少token参数',
                    'data' => null
                ], 400);
            }

            // 模拟退出登录
            return response()->json([
                'code' => 200,
                'message' => '退出登录成功',
                'data' => null
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'code' => 500,
                'message' => '服务器错误',
                'data' => null
            ], 500);
        }
    }
}
